/**
 * Created by perqin on 16-12-6.
 */

'use strict';

/**
 * Module dependencies
 */
var mongoose = require('mongoose'),
  passport = require('passport'),
  User = mongoose.model('User');

/**
 * Create sessions to signin
 */
exports.create = function (req, res, next) {
  passport.authenticate('multi', function (err, user, info) {
    if (err || !user) {
      // NOTE: Failing to send SMS should be covered by 'err', not 'info'
      // NOTE: user will be 'true' in 'sms' response
      return res.status(422).send(info);
    }
    if (req.body.type === 'trial') {
      return req.login(user, function (err) {
        if (err) return res.status(400).send(err);
        return res.status(200).json(user);
      });
    }
    if (req.body.type === 'sms') {
      return res.status(200).send();
    }
    if (req.body.type === 'sms_code') {
      return req.login(user, function (err) {
        if (err) {
          return res.status(400).send(err);
        }
        return res.status(200).json(user);
      });
    }
  })(req, res, next);
};

/**
 * Delete session to signout
 */
exports.delete = function (req, res) {
  req.logout();
  res.status(200).send();
};
